/*
 * inotify-sync - a simple file synchronizer and file system watcher
 * Copyright (C) 2010-2011, inotify-sync developers and inotify-sync contributors
 * Copyright (C) 2010-2011, Cohesion Network Security Studio
 *
 * inotify-sync is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * inotify-sync is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with inotify-sync; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

/*
 * FILE:		ConfigFileParser.cpp
 * USAGE:		---
 * DESCRIPTION:		---
 * OPTIONS:		---
 * REQUIREMENTS:	---
 * BUGS:		---
 * NOTES:		---
 * AUTHOR:		LI Yiwei (mail:leeyiw@gmail.com)
 * COMPANY:		---
 * VERSION:		1.0
 * CREATED:		Sat Nov 19 17:09:10 CST 2011
 * REVISION:		---
 */

#include "ConfigFileParser.h"

ConfigFileParser::ConfigFileParser()
try
{
	if((fp=fopen(CONF_PATH,"r"))==NULL)
	{
		throw Error(errno,E_CONFFOPENERR);
	}
}
catch(Error& error)
{
	error.print_error();
	exit(error.get_error_id());
}

ConfigFileParser::~ConfigFileParser()
{
	fclose(fp);
}

void
ConfigFileParser::get_config(Config& config)
{
	std::string opt_str;
	memset(buf,NULL,sizeof(buf));
	while(NULL!=fgets(buf,sizeof(buf),fp))
	{
		if(is_note(buf))
			continue;
		else
		{
			opt_str=string(buf);
			std::string::size_type equal_pos=opt_str.find('=');
			std::string::size_type end_pos=opt_str.find('\n');
			if(equal_pos==std::string::npos)
				continue;
			opt o;
			o.opt_name=opt_str.substr(0,equal_pos);
			std::string::size_type val_len=end_pos-equal_pos-1;
			o.opt_value=opt_str.substr(equal_pos+1,val_len);
			opt_vec.push_back(o);
		}
		memset(buf,NULL,sizeof(buf));
	}
	config.get_opt(opt_vec);
	/*
	for(size_t i=0;i<opt_vec.size();i++)
	{
		printf("%s=",opt_vec[i].opt_name.c_str());
		printf("%s\n",opt_vec[i].opt_value.c_str());
	}
	*/
}

bool
ConfigFileParser::is_note(char *buf)
{
	if(buf[0]=='#')
		return true;
	return false;
}
